package ru.dc.gui.swing.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Кастомизированный компонент для отображения вкладки в JTabbedPane
 * <pre>
 * User: Penkov Vladimir
 * Date: 01.11.2010
 * Time: 13:51:32
 * </pre>
 */
public class ClosableTabComponent extends JPanel {

    private JButton closeBtn = new JButton();
    private JLabel caption = new JLabel();
    private JTabbedPane pane;
    private Component component;

    public ClosableTabComponent(JTabbedPane tabbedPane, Component comp) {

        this.pane = tabbedPane;
        this.component = comp;

        caption.setMaximumSize(new Dimension(200, caption.getMaximumSize().height));
        caption.setHorizontalAlignment(SwingConstants.CENTER);

        closeBtn.setPreferredSize(new Dimension(16, 16));
        closeBtn.setMaximumSize(new Dimension(16, 16));
        closeBtn.setBorderPainted(false);
        closeBtn.setFocusable(false);
        closeBtn.setOpaque(false);
        closeBtn.setIcon(IconLoader.getInstance().getIcon("close-normal.gif"));
        closeBtn.setRolloverIcon(IconLoader.getInstance().getIcon("close-hover.gif"));
        closeBtn.setPressedIcon(IconLoader.getInstance().getIcon("close-pressed.gif"));
        closeBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        setLayout(new BorderLayout(10, 0));
        setPreferredSize(new Dimension(150, 20));
        setMaximumSize(new Dimension(250, 20));
        add(caption, BorderLayout.CENTER);
        add(closeBtn, BorderLayout.EAST);

        setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
        setFocusable(false);
        setOpaque(false);
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()==1 && SwingUtilities.isLeftMouseButton(e)) {
                    pane.setSelectedComponent(component);
                }
            }
        });
    }

    public void setTitle(String title) {
        caption.setText(title);
        setToolTipText(title);
    }

    public void setIcon(Icon icon) {
        caption.setIcon(icon);
    }

    public JButton getCloseBtn() {
        return closeBtn;
    }

    public JLabel getCaption() {
        return caption;
    }
}
